package com.rongshu.sendmessage.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.Animatable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.drawee.backends.pipeline.PipelineDraweeControllerBuilder;
import com.facebook.drawee.controller.BaseControllerListener;
import com.facebook.imagepipeline.image.ImageInfo;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.rongshu.sendmessage.R;
import com.rongshu.sendmessage.base.BaseActivity;
import com.rongshu.sendmessage.base.MyApplication;
import com.rongshu.sendmessage.bean.UserInfoBean;
import com.rongshu.sendmessage.util.ClientPublicParamUtil;
import com.rongshu.sendmessage.util.DialogUtil;
import com.rongshu.sendmessage.util.ObjectUtil;
import com.rongshu.sendmessage.util.ToastUtils;
import com.rongshu.sendmessage.util.addimage.UpFileUtil;
import com.rongshu.sendmessage.util.httpUtil.Common;
import com.rongshu.sendmessage.util.httpUtil.HYContent;
import com.rongshu.sendmessage.util.httpUtil.IModel;
import com.rongshu.sendmessage.view.bottomView.HeadImageBottomDialog;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import me.relex.photodraweeview.PhotoDraweeView;

import static com.lzy.imagepicker.ui.ImageGridActivity.EXTRAS_IMAGES;
import static com.rongshu.sendmessage.util.DialogUtil.hideProgress;
import static com.rongshu.sendmessage.util.DialogUtil.showProgress;

public class SetUserHeadActivity extends BaseActivity implements HeadImageBottomDialog.UpImageBackLisner {

    private final int REQUEST_CODE = 856;
    private String userPortraitUri;
    private PhotoDraweeView photoDraweeView;
    private String userId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext=this;
        setContentView(R.layout.activity_set_user_head);
        initView();
        userId=MyApplication.mSettings.getString(HYContent.UserId,"");
        initData();
    }

    private void initData() {
        showProgress(mContext);
        Map<String, String> param = new HashMap<>();
//        String userId= MyApplication.mSettings.getString(HYContent.UserId,"");
        param.put("userId",userId);
        param.put("clientPublicParam", ClientPublicParamUtil.getPublicParams(mContext));
        String url= new HYContent().MY_HOME_DATA_URL;
        OkGo.<String>post(url).params(param).execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                IModel.AjaxResult jr = new IModel.AjaxResult(response.body(),false);
                final int code = jr.getCode();
                if(code > 0) {
                    hideProgress();
                    UserInfoBean bean = JSON.parseObject(JSON.toJSONString(jr.getData()), UserInfoBean.class);
                    userPortraitUri=bean.getImgUrl();
                    setView();
                }else{
                    ToastUtils.show(mContext,jr.getMsg());
                    hideProgress();
                }
            }
            @Override
            public void onError(Response<String> response) {
                ToastUtils.show(mContext,"操作失败");
                hideProgress();
            }
        });
    }

    private void setView() {
        PipelineDraweeControllerBuilder controller = Fresco.newDraweeControllerBuilder();
        controller.setUri(userPortraitUri);
        controller.setOldController(photoDraweeView.getController());
        controller.setControllerListener(new BaseControllerListener<ImageInfo>() {
            @Override
            public void onFinalImageSet(String id, ImageInfo imageInfo, Animatable animatable) {
                super.onFinalImageSet(id, imageInfo, animatable);
                if (imageInfo == null) {
                    return;
                }
                photoDraweeView.update(imageInfo.getWidth(), imageInfo.getHeight());
            }
        });
        photoDraweeView.setController(controller.build());
    }

    private void initView() {
        photoDraweeView=findViewById(R.id.phone_drawee_view);
        photoDraweeView.setBackgroundColor(Color.BLACK);
        TextView title=findViewById(R.id.title);
        ImageView titleImgRight = findViewById(R.id.titleImgRight);
        titleImgRight.setImageResource(R.mipmap.more_icon);

        LinearLayout titleLayRight = findViewById(R.id.titleLayRight);
        titleLayRight.setOnClickListener(view->showBottomDialog());
        titleLayRight.setVisibility(View.VISIBLE);

        LinearLayout titleLayLeft = findViewById(R.id.titleLayLeft);
        titleLayLeft.setOnClickListener(view->finish());
        title.setText("设置头像");
    }

    private void showBottomDialog() {
        HeadImageBottomDialog dialog=new HeadImageBottomDialog(userPortraitUri,this);
        dialog.showDialog(mContext);
    }

    @Override
    public void upImageBack() {
//        initData();
        int result = ActivityCompat.checkSelfPermission(mContext, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (result == PackageManager.PERMISSION_DENIED) {//PERMISSION_GRANTED
            String[] permissions = {/*Manifest.permission.WRITE_EXTERNAL_STORAGE,*/
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE};
            ActivityCompat.requestPermissions((BaseActivity)mContext, permissions, 11);
        } else {
            startPhotoSelector();
        }


    }

    private ArrayList<ImageItem> images = new ArrayList<>();
    private void startPhotoSelector() {
        Intent intent = new Intent(this, ImageGridActivity.class);
        intent.putExtra(EXTRAS_IMAGES, images);
        startActivityForResult(intent, REQUEST_CODE);
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            if (data != null && requestCode == REQUEST_CODE) {
                images.clear();
                ArrayList<ImageItem> images1=(ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                images.addAll(images1);
                if (images!=null&&images.size()>0){
                    showProgress(mContext);
                    String path=images.get(0).path;
                    File file=new File(path);
                    Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
                    upLoadImg(bitmap,file);
                }
            } else {
                Toast.makeText(this, "没有数据", Toast.LENGTH_SHORT).show();
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
    @SuppressLint("HandlerLeak")
    private void upLoadImg(Bitmap bitmap,File file) {
//上传图片
        UpFileUtil.upFile(new HYContent().SET_USER_HEAD_URL,bitmap,file,new Handler(){
            @Override
            public void handleMessage(@SuppressLint("HandlerLeak") @NonNull Message msg) {
                super.handleMessage(msg);
                if(msg.what==UpFileUtil.SAVE_SUCCESS){
                    String body=msg.obj+"";
                    Log.e("upFile","上传成功" + body);
                    hideProgress();
                    initData();
                }else if (msg.what==UpFileUtil.SAVE_FIAL){
                    hideProgress();
                }
            }
        });
    }
}